package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQueryObject;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{

    @Autowired
    private StrategyCommentMongoRepository repository;

    public void save(StrategyComment strategyComment) {
        strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);

    }

    public Page<StrategyComment> query(StrategyCommentQueryObject qo) {
        //分页 从0开始
        Pageable pageable= PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize());

        return repository.findByDetailId(qo.getDetailId(),pageable);
    }

    /**
     *
     * @param toId  Mongdb的主键值   _id
     * @param fromId  当前用户id.
     */
    public void strategyThumbup(String toId, Long fromId) {

        //根据id查询评论对象.
        Optional<StrategyComment> op = repository.findById(toId);
        op.ifPresent(commont->{
            //取出评论点赞列表
            List<Long> thumbuplist = commont.getThumbuplist();
            //判断当前点赞列表是否含有当前点赞对象的id
            if(thumbuplist.contains(fromId)){
                //包含--取消点赞
                thumbuplist.remove(fromId);
            }else {
                //不包含--点赞
                thumbuplist.add(fromId);
            }
            //设置点赞数
            commont.setThumbupnum(thumbuplist.size());
            //更新评论
            repository.save(commont);
        });



    }


}
